package com.android.jianboshi.ui.activity;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanResult;
import android.text.TextUtils;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.android.baselibrary.interface_.CommCallBack;
import com.android.baselibrary.tool.CommToast;
import com.android.baselibrary.tool.Log;
import com.android.baselibrary.tool.SPUtil;
import com.android.baselibrary.view.Comm_HeadView;
import com.android.baselibrary.view.MultiStateView;
import com.android.jianboshi.MyApplication;
import com.android.jianboshi.R;
import com.android.jianboshi.adapter.BlueToothListAdapter;
import com.android.jianboshi.constants.SPConstants;
import com.android.jianboshi.event.Event_Notification;
import com.android.jianboshi.manager.BluetoothHelper;
import com.blankj.utilcode.util.ConvertUtils;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

public class Device_ListActivity extends BaseActivity {

    @BindView(R.id.multiplestatusView)
    MultiStateView multiplestatusView;
    @BindView(R.id.recyclerview)
    RecyclerView recyclerview;
    @BindView(R.id.smartrefreshlayout)
    SmartRefreshLayout smartrefreshlayout;
    @BindView(R.id.comm_title)
    Comm_HeadView comm_title;
    @BindView(R.id.iv_loading)
    ImageView iv_loading;

    BlueToothListAdapter adapter;

    List<String> deviceList = new ArrayList<>();
    BluetoothAdapter mBluetoothAdapter;
    BluetoothLeScanner mBLEScanner;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_devicelist;
    }

    @Override
    protected void initView() {
        comm_title.setTitle(getString(R.string.bind_mac));

        recyclerview.setLayoutManager(new LinearLayoutManager(mContext));
        adapter = new BlueToothListAdapter(mContext, callBack);
        recyclerview.setAdapter(adapter);
        adapter.setData(deviceList);

        smartrefreshlayout.setEnableLoadMore(false);
        smartrefreshlayout.setEnableRefresh(false);

        rotate();


        initBluTooth();


    }

    //初始化蓝牙
    BluetoothHelper bluetoothHelper;

    private void initBluTooth() {
        bluetoothHelper = new BluetoothHelper();
        if (bluetoothHelper.isOpen()) {
            Log.d("bt isOpen");
            bluetoothHelper.scan();
        } else {
            Log.d("bt not Open");
        }

        bluetoothHelper.setBroadCastCallback(new BluetoothHelper.BroadCastCallback() {
            @SuppressLint("MissingPermission")
            @Override
            public void onReceiverData(ScanResult result) {
                String deviceName = result.getDevice().getName();
                //先过滤自己设备
                if (TextUtils.isEmpty(deviceName)) return;
                if (!deviceName.startsWith("GYMSTR")) {
                    return;
                }
                boolean has = false;
                for (int i = 0; i < deviceList.size(); i++) {
                    if (deviceList.get(i).equals(deviceName)) {
                        has = true;
                    }
                }
                if (!has) {
                    deviceList.add(deviceName);
                    adapter.notifyDataSetChanged();
                    Log.i("扫描到设备：" + deviceName);
                }
            }
        });
    }

    CommCallBack callBack = new CommCallBack() {
        @Override
        public void onResult(Object obj) {
            String deviceName = (String) obj;
            SPUtil.putValue(mContext, SPConstants.DeviceName, deviceName);
            CommToast.showToast(mContext, getString(R.string.setting_save_success));
            finish();
        }
    };

    @Override
    protected void initData() {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        bluetoothHelper.stopScan();
    }

    //    @Override
//    protected boolean isRegistEventbus() {
//        return true;
//    }

//    @Subscribe(threadMode = ThreadMode.MAIN)
//    public void onEventMainThread(Event_Notification event) {
//        String deviceName = event.deviceName;
//        boolean has = false;
//        for (int i = 0; i < deviceList.size(); i++) {
//            if (deviceList.get(i).equals(deviceName)) {
//                has = true;
//            }
//        }
//        if (!has) {
//            deviceList.add(deviceName);
//            adapter.notifyDataSetChanged();
//            Log.i("扫描到设备：" + deviceName);
//        }
//    }

//
//
//
//    private final ScanListener scanListener = new ScanListener() {
//        @Override
//        public void onScanStart() {
//            Log.i("test", "开始扫描");
//            rotate();
//        }
//
//        @Override
//        public void onScanStop() {
//            Log.i("test", "结束扫描");
//            stopRotate();
//        }
//
//        @Override
//        public void onScanResult(@NonNull Device device, boolean isConnectedBySys) {
//            if (TextUtils.isEmpty(device.getName())) return;
//            Log.i("device.getName():"+ device.getName());
//            if(!"GYMSTR".equals(device.getName()))
//            {
//                return;
//            }
//
//            boolean has = false;
//            for (int i = 0; i < deviceList.size(); i++) {
//                if (deviceList.get(i).getName().equals(device.getName())) {
//                    has = true;
//                }
//            }
//            if (!has) {
//                deviceList.add(device);
//                adapter.notifyDataSetChanged();
//                Log.i("扫描到设备：" + device.getName());
//            }
//        }
//
//        @Override
//        public void onScanError(int errorCode, @NotNull String errorMsg) {
//            switch (errorCode) {
//                case ScanListener.ERROR_LACK_LOCATION_PERMISSION://缺少定位权限
//                    // ToastUtils.showShort("缺少定位权限");
//                    break;
//                case ScanListener.ERROR_LOCATION_SERVICE_CLOSED://位置服务未开启
//                    //               ToastUtils.showShort("位置服务未开启");
//                    break;
//                case ScanListener.ERROR_LACK_SCAN_PERMISSION://缺少搜索权限
//                    //  ToastUtils.showShort("缺少搜索权限");
//                    break;
//                case ScanListener.ERROR_LACK_CONNECT_PERMISSION://缺少连接权限
//                    //  ToastUtils.showShort("缺少连接权限");
//                    break;
//                case ScanListener.ERROR_SCAN_FAILED://搜索失败
//                    //   ToastUtils.showShort("搜索出错：" + errorCode);
//                    break;
//            }
//            Log.i("errorCode:" + errorCode);
//        }
//    };
//
//    //刷新数据
//    private void refreshData() {
//        deviceList.clear();
//        adapter.notifyDataSetChanged();
//
//        if (EasyBLE.getInstance().isInitialized()) {
//            EasyBLE.getInstance().scanConfiguration.setScanPeriodMillis(60 * 1000);
//            if (EasyBLE.getInstance().isScanning()) {
//                EasyBLE.getInstance().stopScanQuietly();
//            }
//            EasyBLE.getInstance().startScan();
//        }
//    }
//
//    //需要进行检测的权限
//    private List<String> getNeedPermissions() {
//        List<String> list = new ArrayList<>();
//        //target sdk版本在29以上的需要精确定位权限才能搜索到蓝牙设备
//        if (getApplicationInfo().targetSdkVersion >= 29) {
//            list.add(Manifest.permission.ACCESS_FINE_LOCATION);
//            list.add(Manifest.permission.ACCESS_COARSE_LOCATION);
//        } else {
//            list.add(Manifest.permission.ACCESS_COARSE_LOCATION);
//        }
//        //Android 12需要
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
//            list.add(Manifest.permission.BLUETOOTH_SCAN);
//            list.add(Manifest.permission.BLUETOOTH_CONNECT);
//            list.add(Manifest.permission.ACCESS_COARSE_LOCATION);
//        }
//        return list;
//    }
//
//    @Override
//    protected void onPause() {
//        super.onPause();
//        if (EasyBLE.getInstance().isInitialized()) {
//            EasyBLE.getInstance().stopScan();
//        }
//    }
//
//    //点击事件
//    @OnClick({R.id.iv_loading})
//    public void onViewClicked(View view) {
//        switch (view.getId()) {
//            case R.id.iv_loading:
//                refreshData();
//                break;
//        }
//    }
//
    private void rotate() {
        Log.i("开始动画");
        RotateAnimation ra = new RotateAnimation(0, 360, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        ra.setInterpolator(new LinearInterpolator());
        ra.setRepeatMode(Animation.RESTART);
        ra.setRepeatCount(Animation.INFINITE);
        ra.setDuration(1000);
        iv_loading.startAnimation(ra);
    }
//
//    private void stopRotate() {
//        Log.i("结束动画");
//        iv_loading.clearAnimation();
//    }
}
